<?php
// 确保会话启动
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
// 如果用户没有登录或角色不是 "admin"，则重定向到登录页面
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    // 使用 ob_start() 防止输出缓冲区的干扰
    ob_start(); 
    header('Location: http://localhost/Library_management_system/index.php');
    exit();
}
// 包含数据库和计算罚金的函数
include_once 'D:/bee/wamp64/www/Library_management_system/forms/functions.php';


// 数据库连接
try {
    $pdo = new PDO('mysql:host=localhost;dbname=library', 'root', '123456');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("数据库连接失败: " . $e->getMessage());
}

// 处理搜索请求
$u_No = '';
$records = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['u_No'])) {
    $u_No = $_POST['u_No'];

    // 查询指定读者的借阅记录
    $sql = "
        SELECT l.Loan_Id, l.book_No, l.loan_date, l.Return_date, l.state_ID, 
               DATE_ADD(l.loan_date, INTERVAL 1 MONTH) AS due_date, s.state_description, u.u_No AS user_id
        FROM Loan AS l
        INNER JOIN book AS b ON l.book_No = b.book_No
        INNER JOIN state AS s ON l.state_ID = s.state_ID
        INNER JOIN users AS u ON l.u_No = u.u_No
        WHERE l.u_No = :u_No
        ORDER BY l.loan_date DESC
    ";

    // 使用参数绑定来防止 SQL 注入攻击
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':u_No', $u_No, PDO::PARAM_STR);
    
    // 执行查询
    $stmt->execute();
    
    // 获取结果
    $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// 获取当前日期
$currentDate = date('Y-m-d');
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>查看所有用户的借阅记录</title>
</head>
<body>
    <h2>查看所有用户的借阅记录</h2>

    <!-- 搜索表单 -->
    <form method="POST">
        <label for="u_No">输入读者账号 (u_No):</label>
        <input type="text" id="u_No" name="u_No" value="<?php echo htmlspecialchars($u_No); ?>" required>
        <button type="submit">搜索</button>
    </form>

    <?php if (count($records) > 0): ?>
        <ul>
            <?php foreach ($records as $record): 
                $loanDate = $record['loan_date'];
                $returnDate = $record['Return_date'];
                $dueDate = $record['due_date'];
                $fine = 0.0;

                // 计算罚金
                if ($returnDate === null) {
                    if ($currentDate > $dueDate) {
                        // 图书未归还且逾期
                        $fine = calculateFine($dueDate, null, $currentDate);
                        $status = '超期未归还';
                    } else {
                        // 图书未归还且未逾期
                        $fine = 0.0;
                        $status = '已借阅';
                    }
                } else {
                    // 图书已经归还
                    $fine = calculateFine($dueDate, $returnDate, $currentDate);
                    if ($returnDate > $dueDate) {
                        $status = '超期归还';
                    } else {
                        $status = '正常归还';
                    }
                }
            ?>
                <li>
                    用户ID: <?php echo htmlspecialchars($record['user_id']); ?>, 
                    书籍ID: <?php echo htmlspecialchars($record['book_No']); ?>, 
                    借阅日期: <?php echo htmlspecialchars($loanDate); ?>, 
                    归还日期: <?php echo $returnDate ? htmlspecialchars($returnDate) : '未归还'; ?>, 
                    状态: <?php echo htmlspecialchars($record['state_description']); ?>, 
                    罚金: ￥<?php echo number_format($fine, 2); ?>
                </li>
            <?php endforeach; ?>
        </ul>
    <?php elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($u_No)): ?>
        <p>没有找到该用户的借阅记录。</p>
    <?php else: ?>
        <p>请输入读者账号进行查询。</p>
    <?php endif; ?>
</body>
</html>
